﻿#include "RenderTexture.hpp"
#include "Shader.hpp"
#include <iostream>

namespace phx
{

RenderTexture::RenderTexture(unsigned int width, unsigned int height)
{
	glGenFramebuffers(1, &mFrameBuffer);
	glBindFramebuffer(GL_FRAMEBUFFER, mFrameBuffer);

	glGenTextures(1, &mTexColorBuffer);
	glBindTexture(GL_TEXTURE_2D, mTexColorBuffer);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, mTexColorBuffer, 0);

	glGenRenderbuffers(1, &mRboDepthStencil);
	glBindRenderbuffer(GL_RENDERBUFFER, mRboDepthStencil);
	glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, width, height);
	glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, mRboDepthStencil);

	glBindFramebuffer(GL_FRAMEBUFFER, NULL);
}

void RenderTexture::use(RenderTexture &renderTexture)
{
	glBindFramebuffer(GL_FRAMEBUFFER, renderTexture.mFrameBuffer);
}

void RenderTexture::use()
{
	glBindFramebuffer(GL_FRAMEBUFFER, NULL);
}

void RenderTexture::render()
{
	glBindFramebuffer(GL_FRAMEBUFFER, NULL);
	glDisable(GL_DEPTH_TEST);
	glDisable(GL_CULL_FACE);
	DefaultShader::renderTexture.use();

	//glActiveTexture(GL_TEXTURE0);
	glBindTexture(GL_TEXTURE_2D, mTexColorBuffer);

	glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
}

void RenderTexture::clear()
{
	glBindFramebuffer(GL_FRAMEBUFFER, mFrameBuffer);
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
}

RenderTexture::~RenderTexture()
{
	glDeleteFramebuffers(1, &mFrameBuffer);
	glDeleteTextures(1, &mTexColorBuffer);
	glDeleteRenderbuffers(1, &mRboDepthStencil);
}

}